import datetime
import time
import os

import htmllib, formatter, urllib, urlparse

DBG = 0
TRC = 1
WARN = 2
ERR = 3

LOG_LEVEL = DBG
LOG_TYPE_INFO = {DBG:"DEBUG", TRC:"TRACE", WARN:"WARNING", ERR:"ERROR"}

class Log(object):

    @classmethod
    def init(cls):
        dateStr = Log.getEscapedDateStr()
        cwd = os.getcwd() + "\\..\\log"
        format = '%s\\log(%s)_%s.txt'
        try:
            Log.trace_file = os.open(format % (cwd, dateStr, LOG_TYPE_INFO[TRC]), os.O_RDWR|os.O_APPEND)
        except:
            Log.trace_file = os.open(format % (cwd, dateStr, LOG_TYPE_INFO[TRC]), os.O_RDWR|os.O_CREAT)
        try:
            Log.error_file = os.open(format % (cwd, dateStr, LOG_TYPE_INFO[ERR]), os.O_RDWR|os.O_APPEND)
        except:
            Log.error_file = os.open(format % (cwd, dateStr, LOG_TYPE_INFO[ERR]), os.O_RDWR|os.O_CREAT)
        
        dateStr = Log.getDateStr() + " " + Log.getTimeStr()
        os.write(Log.error_file, "\n\n\n===============================================================\n")
        os.write(Log.error_file, "        Log for " + dateStr + "\n\n")
        os.write(Log.trace_file, "\n\n\n===============================================================\n")
        os.write(Log.trace_file, "        Log for " + dateStr + "\n\n")
        

    @classmethod
    def close(cls):
        os.close(Log.trace_file)
        os.close(Log.error_file)

    @classmethod
    def getEscapedDateStr(cls):
        #dateStr = Log.getDateStr() + "_" + Log.getTimeStr()
        dateStr = Log.getDateStr()
        dir = ""
        for ch in dateStr:
            if ch == ":":
                dir += "-"
            else:
                dir += ch
        return dir

    @classmethod
    def getTimeStr(cls):
        timeStr = time.strftime('%X')
        return timeStr

    @classmethod
    def getDateStr(cls):
        today = datetime.date.today();
        dateStr = today.strftime('%Y-%m-%d')
        return dateStr

    @classmethod
    def log(cls, logType, msg):
        if (logType >= LOG_LEVEL) or ((LOG_LEVEL >= TRC) and (logType >= TRC)):
            msg = "[%s]: %s" %(LOG_TYPE_INFO[logType], msg)
            print msg
            msg += "\n"
            os.write(Log.trace_file, msg)
            if logType >= WARN:
                os.write(Log.error_file, msg)

    @classmethod
    def d(cls, msg):
        Log.log(DBG, msg)

    @classmethod
    def t(cls, msg):
        Log.log(TRC, msg)

    @classmethod
    def w(cls, msg):
        Log.log(WARN, msg)

    @classmethod
    def e(cls, msg):
        Log.log(ERR, msg)


if __name__ == '__main__':
    Log.init()
    Log.log(DBG, "Hello, debug")
    Log.log(TRC, "Hello, trace")
    Log.log(WARN, "Hello, warning")
    Log.log(ERR, "Hello, error")
    Log.close()